package com.springboot.controller;

import java.util.concurrent.Future;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.springboot.async.TestAsync;
import com.springboot.bean.TestBean;
import com.springboot.service.in.TestIn;

@RestController
@RequestMapping("/test")
public class TestController {

	@Autowired
	@Qualifier("Test1Impl")
	private TestIn test1In;

	@Autowired
	@Qualifier("Test2Impl")
	private TestIn test2In;

	@Autowired
	private TestAsync task;

	@RequestMapping(value = "/getTestBeanById/{id}", method = RequestMethod.POST)
	public TestBean getTestBeanById(@PathVariable int id, @RequestParam(required = true) int type) throws Exception {
		TestBean testBean = null;
		if (type == 1) {
			testBean = test1In.getTestBeanById("test", id);
		} else if (type == 2) {
			testBean = test2In.getTestBeanById("test", id);
		}

		long start = System.currentTimeMillis();
		Future<String> task1 = task.doTaskOne();
		Future<String> task2 = task.doTaskTwo();
		Future<String> task3 = task.doTaskThree();
		while (true) {
			if (task1.isDone() && task2.isDone() && task3.isDone()) {
				// 三个任务都调用完成，退出循环等待
				break;
			}
			System.err.println("等待三个任务都调用完成");
			Thread.sleep(1000);
		}
		long end = System.currentTimeMillis();
		System.out.println("任务全部完成，总耗时：" + (end - start) + "毫秒");

		return testBean == null ? new TestBean() : testBean;
	}

}
